package com.stx.jeepay.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.stx.jeepay.core.dao.MchPayPassageDao;
import com.stx.jeepay.core.entity.MchPayPassageEntity;
import com.stx.jeepay.core.entity.PayInterfaceDefineEntity;
import com.stx.jeepay.core.enums.CS;
import com.stx.jeepay.core.expection.BizException;
import com.stx.jeepay.core.service.MchPayPassageService;
import com.stx.jeepay.core.service.PayInterfaceDefineService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;


@Service("mchPayPassageService")
public class MchPayPassageServiceImpl extends ServiceImpl<MchPayPassageDao, MchPayPassageEntity> implements MchPayPassageService {

    @Autowired
    private PayInterfaceDefineService payInterfaceDefineService;

    /**
     * 根据支付方式查询可用的支付接口列表
     */
    @Override
    public List<JSONObject> selectAvailablePayInterfaceList(String wayCode, String appId, Byte infoType, Byte mchType) {
        Map params = new HashMap();
        params.put("wayCode", wayCode);
        params.put("appId", appId);
        params.put("infoType", infoType);
        params.put("mchType", mchType);
        List<JSONObject> list = baseMapper.selectAvailablePayInterfaceList(params);
        if (CollUtil.isEmpty(list)) {
            return null;
        }

        // 添加通道状态
        for (JSONObject object : list) {
            MchPayPassageEntity payPassage = baseMapper.selectOne(new LambdaQueryWrapper<MchPayPassageEntity>()
                    .eq(MchPayPassageEntity::getAppId, appId)
                    .eq(MchPayPassageEntity::getWayCode, wayCode)
                    .eq(MchPayPassageEntity::getIfCode, object.getString("ifCode")));
            if (payPassage != null) {
                object.put("passageId", payPassage.getId());
                if (payPassage.getRate() != null) {
                    object.put("rate", payPassage.getRate().multiply(new BigDecimal("100")));
                }
                object.put("state", payPassage.getState());
            }
            if (object.getBigDecimal("ifRate") != null) {
                object.put("ifRate", object.getBigDecimal("ifRate").multiply(new BigDecimal("100")));
            }
        }
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdateBatchSelf(List<MchPayPassageEntity> mchPayPassageList, String mchNo) {
        for (MchPayPassageEntity payPassage : mchPayPassageList) {
            if (payPassage.getState() == CS.NO && payPassage.getId() == null) {
                continue;
            }
            if (StringUtils.isNotBlank(mchNo)) {
                payPassage.setMchNo(mchNo);
            }
            if (payPassage.getRate() != null) {
                payPassage.setRate(payPassage.getRate().divide(new BigDecimal("100"), 6, BigDecimal.ROUND_HALF_UP));
            }
            if (!saveOrUpdate(payPassage)) {
                throw new BizException("操作失败");
            }
        }
    }

    /**
     * 根据应用ID 和 支付方式， 查询出商户可用的支付接口
     **/
    @Override
    public MchPayPassageEntity findMchPayPassage(String mchNo, String appId, String wayCode) {
        List<MchPayPassageEntity> list = list(new LambdaQueryWrapper<MchPayPassageEntity>()
                .eq(MchPayPassageEntity::getMchNo, mchNo)
                .eq(MchPayPassageEntity::getAppId, appId)
                .eq(MchPayPassageEntity::getState, CS.YES)
                .eq(MchPayPassageEntity::getWayCode, wayCode));
        if (CollUtil.isEmpty(list)) {
            return null;
        } else {
            // 返回一个可用通道
            HashMap<String, MchPayPassageEntity> mchPayPassageMap = new HashMap<>();
            for (MchPayPassageEntity mchPayPassage : list) {
                mchPayPassageMap.put(mchPayPassage.getIfCode(), mchPayPassage);
            }
            // 查询ifCode所有接口
            PayInterfaceDefineEntity payInterfaceDefine = payInterfaceDefineService.getOne(new LambdaQueryWrapper<PayInterfaceDefineEntity>()
                    .select(PayInterfaceDefineEntity::getIfCode, PayInterfaceDefineEntity::getState)
                    .eq(PayInterfaceDefineEntity::getState, CS.YES)
                    .in(PayInterfaceDefineEntity::getIfCode, mchPayPassageMap.keySet()), false);

            if (payInterfaceDefine!=null){
                return mchPayPassageMap.get(payInterfaceDefine.getIfCode());
            }
        }
        return null;
    }
}